package runninbuddy;

import java.io.IOException;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.location.QualifiedCoordinates;

import net.rim.device.api.gps.BlackBerryLocation;
import net.rim.device.api.io.URI;
import net.rim.device.api.system.AccelerometerData;

public class DataLogger implements Runnable {

	private final DataStore store;
	private OutputStream _ostream;
	private volatile boolean alive;

	public DataLogger(DataStore store, URI fileName) throws IOException {
		this.store = store;
		FileConnection fconn = (FileConnection) Connector.open(fileName
				.toString());
		if (!fconn.exists())
			fconn.create();
		_ostream = fconn.openOutputStream();
		fconn.close();
		alive = true;
	}

	public synchronized void stop() throws IOException {
		alive = false;
		if (_ostream != null) {
			_ostream.close();
			_ostream = null;
		}
	}

	private synchronized void log(RunnerData element) throws IOException {
		if (_ostream != null) {
			BlackBerryLocation location = element.bbLocation;
			QualifiedCoordinates coordinates = location
					.getQualifiedCoordinates();
			AccelerometerData accData = element.accData;

			StringBuffer sb = new StringBuffer();
			sb.append(location.getTimestamp());
			sb.append(',');
			sb.append(coordinates.getLongitude());
			sb.append(',');
			sb.append(coordinates.getLatitude());
			sb.append(',');
			sb.append(coordinates.getAltitude());
			sb.append(',');
			sb.append(location.getSpeed());
			sb.append(',');
			sb.append(location.getCourse());
			sb.append(',');
			sb.append(accData.getLastTimestamp());
			sb.append(',');
			sb.append(accData.getLastXAcceleration());
			sb.append(',');
			sb.append(accData.getLastYAcceleration());
			sb.append(',');
			sb.append(accData.getLastZAcceleration());
			sb.append('\n');

			_ostream.write(sb.toString().getBytes());
		}
	}

	public void run() {
		while (alive) {
			RunnerData currentData;
			try {
				currentData = store.take();
				log(currentData);
			} catch (InterruptedException e) {
				System.err.println("DataLogger.run: " + e.getMessage());
			} catch (IOException e) {
				try {
					stop();
				} catch (IOException e1) {
					throw new RunninBuddyException(e1);
				}
				throw new RunninBuddyException(e);
			}
		}
	}
}
